package com.literature.search.core.entity;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

/**
 * @Author: DangKong
 * @Date: 2023/3/3 20:55
 * @Description: 每个文件的单独一页
 */

@Data
@Document(collection = "page_content")
public class PageContent  implements Serializable {

    private static final long serialVersionUID = 1L;



    @Field("file_id")
    @ApiModelProperty(value = "所属文档Id")
    private String fileId;

    @ApiModelProperty(value = "页码")
    @Field("page_number")
    private int pageNumber;

    @Field("content")
    @ApiModelProperty(value = "文件转化成base64编码后所有的内容")
    private String content;

    @Field("thumb_id")
    @ApiModelProperty(value = "预览图的GridFS的ID")
    private String thumbId;



    public void readFile(String path){
        //读文件
        File file = new File(path);
        byte[] bytes = getContent(file);
        //将文件内容转化为base64编码
        this.content = Base64.getEncoder().encodeToString(bytes);
    }

    public void readFile(InputStream inputStream) {
        byte[] bytes = getContent(inputStream);
        //将文件内容转化为base64编码
        this.content = Base64.getEncoder().encodeToString(bytes);
    }

    private byte[] getContent(File file) {
        byte[] bytesArray = new byte[(int) file.length()];
        try (FileInputStream fileInputStream = new FileInputStream(file)){
            if (fileInputStream.read(bytesArray) < 0) {
                return bytesArray;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytesArray;
    }

    private byte[] getContent(InputStream inputStream) {
        byte[] bytesArray = new byte[]{};
        try {
            if (inputStream.read(bytesArray) < 0) {
                return bytesArray;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytesArray;
    }


    public void readOriginText(String textFilePath) throws IOException {
        //读文件
        List<String> stringList = FileUtils.readLines(new File(textFilePath),
                StandardCharsets.UTF_8);
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : stringList) {
            stringBuilder.append(s);
        }
        this.content = stringBuilder.toString();


        //File file = new File(textFilePath);
        //byte[] bytes = getContent(file);
        //// 不转换为base64编码
        //this.content = new String(bytes);
    }
}
